//
//  HLHomeRefreshControl.m
//  weibo-OC
//
//  Created by 黄力 on 15/12/23.
//  Copyright © 2015年 HLTest. All rights reserved.
//

#import "HLHomeRefreshControl.h"
#import <Masonry.h>

#define HomeRefreshControlHeight 60

//状态的枚举
enum HLHomeRefreshControlStatus {
    //下拉刷新状态
    HLHomeRefreshControlStatusNormal,
    //准备刷新状态
    HLHomeRefreshControlStatusPulling,
    //正在刷新状态
    HLHomeRefreshControlStatusRefreshing
};

@interface HLHomeRefreshControl ()

//状态的枚举
@property (nonatomic,assign) enum HLHomeRefreshControlStatus status;
//存储父控件
@property (nonatomic,weak) UIScrollView *superScrollView;
//图片
@property (nonatomic,strong) UIImageView *refreshIconView;
//文字
@property (nonatomic,strong) UILabel *refreshTitleView;
//指示器
@property (nonatomic,strong) UIActivityIndicatorView *refreshIndicatorView;
//记录当前状态
@property (nonatomic,assign) enum HLHomeRefreshControlStatus newStatus;
@end

@implementation HLHomeRefreshControl

- (instancetype)initWithFrame:(CGRect)frame {
    //设置frame
    CGRect rect = CGRectMake(0, - HomeRefreshControlHeight, MainScreenWidth, HomeRefreshControlHeight);
    if (self = [super initWithFrame:rect]) {
        //设置界面
        [self setupUI];
    }
    return self;
}

//设置界面
- (void)setupUI {
    self.backgroundColor = [UIColor redColor];
    //添加子控件
    [self addSubview:self.refreshIconView];
    [self addSubview:self.refreshTitleView];
    [self addSubview:self.refreshIndicatorView];
    //设置约束
    //图片
    [self.refreshIconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self);
        make.centerX.equalTo(self).offset(-40);
    }];
    //文字
    [self.refreshTitleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self);
        make.left.equalTo(self.refreshIconView.mas_right);
    }];
    //指示器
    [self.refreshIndicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.refreshIconView);
    }];
    //隐藏指示器
    self.refreshIndicatorView.hidden = YES;
}

//重写status的setter方法
- (void)setStatus:(enum HLHomeRefreshControlStatus)status {
    _status = status;
    //根据当前枚举值进行设置
    if (status == 0) {
//        NSLog(@"下拉起飞");
        //修改文字
        self.refreshTitleView.text = @"下拉起飞";
        [UIView animateWithDuration:0.25 animations:^{
            self.refreshIconView.transform = CGAffineTransformIdentity;
            //只有上一次状体是刷新时才修改
            if (self.newStatus == 2) {
                //修改显示范围
                UIEdgeInsets edge = self.superScrollView.contentInset;
                edge.top -= HomeRefreshControlHeight;
                self.superScrollView.contentInset = edge;
                self.newStatus = status;
            }
        }];
    }else if (status == 1){
//        NSLog(@"准备起飞");
        self.refreshTitleView.text = @"准备起飞";
        [UIView animateWithDuration:0.25 animations:^{
            self.refreshIconView.transform = CGAffineTransformMakeRotation(M_PI);
        }];
    }else if (status == 2) {
//        NSLog(@"正在起飞");
        self.refreshTitleView.text = @"正在起飞";
        //隐藏图片
        self.refreshIconView.hidden = YES;
        //显示指示器
        self.refreshIndicatorView.hidden = NO;
        //指示器开始动画
        [self.refreshIndicatorView startAnimating];
        //设置触发事件
        [self sendActionsForControlEvents:UIControlEventValueChanged];
        //动画
        [UIView animateWithDuration:0.25 animations:^{
           //修改显示范围
            UIEdgeInsets edge = self.superScrollView.contentInset;
            edge.top += HomeRefreshControlHeight;
            self.superScrollView.contentInset = edge;
        }];
        self.newStatus = status;
    }
    
}

//是否正在刷新
- (BOOL)isRefreshing {
    if (self.status == 2) {
        return YES;
    }
    return NO;
}

//结束刷新
- (void)endRefreshing {
    //延迟
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.status = 0;
        //显示图片
        self.refreshIconView.hidden = NO;
        //隐藏指示器
        self.refreshIndicatorView.hidden = YES;
        //结束动画
        [self.refreshIndicatorView startAnimating];
    });
    
}

//出现在父控件上时调用
- (void)willMoveToSuperview:(UIView *)newSuperview {
    [super willMoveToSuperview:newSuperview];
    //获取父控件
    self.superScrollView = (UIScrollView *)newSuperview;
    //监听父控件的偏移量
    [self.superScrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
}

//监听的属性改变时调用该方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    //计算最大偏移量
    CGFloat offsetMaxY = self.superScrollView.contentInset.top + HomeRefreshControlHeight;
    //当前的偏移量
    CGFloat offsetY = - self.superScrollView.contentOffset.y;
    //根据是否正在拖拽判断
    if ([self.superScrollView isDragging]) {
        //根据偏移量判断
        //正在拖拽过程中,在下拉和准备之间切换
        if (self.status == 1 && offsetY < offsetMaxY) {
            self.status = 0;
        }else if (self.status == 0 && offsetY > offsetMaxY) {
            self.status = 1;
        }
    }else {
        //当时准备状态松手,就刷新
        if (self.status == 1) {
            self.status = 2;
        }
    }
}

#pragma mark - 懒加载
//图片
- (UIImageView *)refreshIconView {
    if (_refreshIconView == nil) {
        _refreshIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tableview_pull_refresh"]];
    }
    return _refreshIconView;
}
//文字
- (UILabel *)refreshTitleView {
    if (_refreshTitleView == nil) {
        _refreshTitleView = [[UILabel alloc] initWithTitle:@"下拉起飞" withTitleFont:14 withTitleColor:[UIColor lightGrayColor]];
    }
    return _refreshTitleView;
}
//指示器
- (UIActivityIndicatorView *)refreshIndicatorView {
    if (_refreshIndicatorView == nil) {
        _refreshIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    }
    return _refreshIndicatorView;
}

//控件销毁时移除通知
- (void)dealloc {
    [self.superScrollView removeObserver:self forKeyPath:@"contentOffset"];
}


@end
